/*pmFWCFu5nhKkBzYmrkBakSAM+Inca+/2SazZgz119uT/d0gZJMONgfRaOvs2SpQg*/
import SyncLoadComp from '../../../utils/SyncLoadComp';
import {referUrls, constProp, statusProp, Urls} from "../../CONSTANCE";
import {queryEnvParamUrl, companyDrawUrl} from "../../dataManage";
import {
    deleteFinanceOrStock, getCurCardStatus, onCardButtonClick, onCardTableButtonClick, onFinanceOrPurchaseCardButtonClick,
    onFinanceTableButtonClick, onStockTableButtonClick,
    querySupFinanceOrStockTableData, setCardButtonStatus, setCardStatus, setFinanceCardBtnStatus
} from './../clickEvent/SupCardButtonAction';
import {
    dealRefTemplateItems, editSupBaseInfo, setCodeAndDeleteStatusFieldLink,  validateAddOrCopy,querySupplierVersion
} from "../../../utils/SupplierUtils";
import {initTabTitle, initChildTabTitle} from './initTabList';
import {base, deepClone, pageTo,ajax} from 'nc-lightapp-front';
const {NCPopconfirm} = base;
let tempData;
/**
 * 创建页面参数
 * @param pagecode
 * @param appcode
 * @returns {*}
 */
const createUIDomParam = function(pagecode, appcode){
    var param  = {pagecode:pagecode};
    return window.location.href.startsWith('http://localhost:3006') ? {...param, appcode: appcode} : param;
};

export default function() {
    const _this = this;
    initLoad.call(this, {
        //模板参数
        tempParam:{...createUIDomParam(this.props.pagecode, pageTo.getAppCode())},
        //多语参数
        langParam:{moduleId: '10140SUG',domainName: 'uapbd'}
    }, ({data,lang}) => {
        this.Lang = lang;//多语资源
        loadComp.call(this, data, lang);
    })
}

/**
* 初始化页面
*
* @Param {tempParam,langParam,...otherLoad}
*      tempParam：模板参数配置
*      langParam：多语参数配置
*      otherLoad：对象数组 每个对象要求都是Promise对象，如：[new Promise((resolve)=>{resolve(true)})]
* @Param callback  加载成功后回调
*/
function initLoad({tempParam,langParam,...otherLoad }={}, callback = () => {}) {
    //模板
    let loadTemp = new Promise((resolve)=>{
        this.props.createUIDom(tempParam,(data)=>{
            resolve(data);
        });
    });
    //多语
    let loadLang = new Promise((resolve)=>{
        this.props.MultiInit.getMultiLang(Object.assign(langParam,{callback:(json, status, inlt)=>{
            this.inlt = inlt;
            resolve(json);
         }}));
     });
    Promise.all([loadTemp,loadLang,...otherLoad]).then((res)=>{
        let [data,lang,...others] = res;

        callback({data,lang,...others});
    }).catch((error)=>{
        throw new Error(error);
    });
}

function loadComp(data, lang) {
    tempData = data;
    SyncLoadComp.call(this,{
        props:this.props,
        urlsArr:Object.values(referUrls),
        success:()=>{afterInitLoad.call(this, lang)},
        fail:()=>{afterInitLoad.call(this, lang)}
    })
}

async function afterInitLoad(lang) {
    this.Lang = lang;//多语资源
    //回调中先设置state,再处理initEnvParam回调
    const param = await queryEnvParamUrl.call(this);
    //获得个性化参数
    this.state.envParam = getInitEnvParamObj.call(this, tempData.context,param.org);
    //个性化设置的org
    this.state.indivOrg = tempData.context;
    this.state.busiPortraitUrl = companyDrawUrl || param.busiPortraitUrl;
    resetStateAfterLoadLang.call(this, modiferMeta);
}

function modiferMeta() {
    let _props = this.props;
    //客户外币汇率类型(基本信息)
    let base_ratetype_item = tempData.template['supplier_baseInfo_card']['items'].find(item => item['attrcode'] === 'ratetype');
    if (!!base_ratetype_item) {
        base_ratetype_item.queryCondition = () => {
            return {
                type:'sup',
                GridRefActionExt: 'nccloud.web.uapbd.customer.baseinfo.extendRef.RatetypeSqlBuilder'
            }
        }
    }
    //客户外币汇率类型(财务信息)
    let finance_ratetype_item = tempData.template['supfinance_card']['items'].find(item => item['attrcode'] === 'ratetype');
    if (!!finance_ratetype_item) {
        finance_ratetype_item.queryCondition = () => {
            return {
                type:'sup',
                GridRefActionExt: 'nccloud.web.uapbd.customer.baseinfo.extendRef.RatetypeSqlBuilder'
            }
        }
    }
    //业务单元过滤
    let pk_org_item = tempData.template['base']['items'].find(item => item['attrcode'] === 'pk_org');
    if (!!pk_org_item) {
        pk_org_item.queryCondition = () => {
            return {
                AppCode: pageTo.getAppCode(),
                TreeRefActionExt: 'nccloud.web.refer.sqlbuilder.PrimaryOrgSQLBuilder'
            }
        }
    }

    //版本化 版本号添加超链接
    tempData.template['versionList'].items = tempData.template['versionList'].items.map((item) => {
        if (item.attrcode === 'version') {
            item.itemtype = 'customer';
            item.render = (text, record) => {
                return (
                    <span
                        style={{ color: '#007ace', cursor: 'pointer' }}
                        onClick={() => {
                            this.props.modal.show('versionCardmodal')
                            querySupplierVersion(record,'',_props);
                        }}
                    >
                        {record && record['values'] && record['values']['version'] && record['values']['version'].value}
                    </span>
                );
            };
        }
        return item;
    });
    //设置页面表格表单编辑性
    setCardEdit.call(this);

    this.props.meta.setMeta(tempData.template,()=>{
        //处理元数据
        dealMetaItems.call(this, tempData.template);
        //使用NCTable,适配模板
        this.meta2TableFieldAdapter('custsupbankacc');
        //适配供应商供货目录联查供应商
        if(this.state.fromListId){
            setTimeout( () => {
                this.state.fromListId && this.setState({directOpenCard:true,relateQueryId:this.state.fromListId},()=>{
                    setCardButtonStatus.call(this,'browse');
                    this.state.relateQueryId && this.initPageData(this.setCardValue,this.setCardStatus, this.props.getUrlParam("isCopy") ? Urls.copySupplierUrl : null);
                });
            }, 0)

        }else{
            ajax({
                url: "/nccloud/uapbd/supplier/querySupplierOidByVid.do",
                data:{
                    pk_supplier_v:this.state.fromLinkId,
                },
                success:(res)=>{
                    if(res.data){
                        res.data && this.setState({directOpenCard:true,relateQueryId:res.data},()=>{
                            setCardButtonStatus.call(this,'browse');
                            this.state.relateQueryId && this.initPageData(this.setCardValue,this.setCardStatus, this.props.getUrlParam("isCopy") ? Urls.copySupplierUrl : null);
                        });
                    }
                }
            })
        }

        //初始页面 设置按钮状态
        this.props.button.setButtons(tempData.button);
    });
}

/**
 * 设置表格表单编辑性
 * @param this
 * @returns {*}
 */
function setCardEdit() {
    const status = this.props.getUrlParam("status"),
        formData = this.props.form.getAllFormValue(this.state.card.form.formId);
    this.props.form.setFormItemsRequired('linkman',{'cell':false});
    validateAddOrCopy.call(this,()=>{
        editSupBaseInfo.call(this,{
            status,
            selectedRecords:[],
            dirtyRecords:this.state.dirtyRecords || [formData.rows[0].values],
            isCopy: this.props.getUrlParam("isCopy")
        });
    })
}

/**
 * 获得初始环境信息
 * @param context
 * @param param
 * @returns {*}
 */
function getInitEnvParamObj(context,param) {
    //是业务单元节点:走个性化，不是业务单元节点：走初始化的参数
    return this.props.nodeType == 'ORG_NODE'?context:{
        pk_org:param.pk_org,
        pk_group:param.pk_group,
        org_Name:param.name
    };
}

/*** 加载多语之后  重置state*/
function resetStateAfterLoadLang(callback) {
    this.state = Object.assign({
        selectType: 'default',
        leftTree:[],
        rightTree:[],
        openCard: true,
        pageInfo:null,//记录列表分页信息
        loadLang:true,//加载多语
        envParam:undefined,//初始参数
        openDialog:false,
        openDeleteDialog:false,
        batchUpdateStepClick:false,//向导批改参数
        assignStepClick:false,//向导分配参数
        loadSupBank:false,//加载银行账户组件
        queryInfo:{logic:"and",conditions:[]},//缓存的查询条件
        newQueryInfo:{logic:"and",conditions:[]},
        directOpenCard:false,
        relateQueryId:null,
        allpks:[],
        busiPortraitUrl:null,//企业画像url
        orgAssignCacheField:{},
        supplierMain:{code:'',name:''},
        selectedRecords:undefined,//列表到卡片所有操作都依赖该对象属性
        dirtyRecords:undefined,//列表到卡片操作辅助属性（在selectedRecords失效时，用这个）
        dblClkRecord:undefined,//卡片 两个关联关系的子表编辑时需要这个对象属性
        queryRecords:[],//表格数据
        status:'browse',
        showBasicTabChild: true,//是否显示基本信息的子页签
        otherParam:undefined,//其他参数（如在userjson中传递的参数）
        //冻结时业务单元参照的参数
        freezeOrgParam:{
            onChange:this.onBusinessUnitChange.bind(this),
            value:null,
            isMultiSelectedEnabled:true,
            fieldid:'businessunittreeref',
            popWindowClassName:'businessunit-zindex',
            isShowUnit:false,
            queryCondition:{
                TreeRefActionExt:'nccloud.web.uapbd.supplier.suprefcondition.action.FreezeBusinessUnitRefSqlBuilder'
            }
        },
        activeTab: 0,
        currMainCode: "supplier_baseInfo_card",
          //卡片
          card:{
            //卡片按钮配置
            buttonConfig:{
               area: constProp.SUP_BASE_CARD,
               buttonLimit: 3,
               onButtonClick: this.onCardButtonClick,
               popContainer: document.querySelector('.supplier_baseInfo_card')
            },
            //卡片表单配置
            form:{
                formName:this.Lang['10140SUG-000135'],/* 国际化处理： 基本信息*/
                formId:constProp.SUP_BASE_CARD,
                primaryKey:'pk_supplier',
                action:{
                    onAfterEvent: this.onAfterCardFormEditEvent.bind(this),
                    onBeforeEvent: this.supplierBasicFormBeforeEvent.bind(this),
                },
                baseFormId: constProp.SUP_BASE_FORM,
            },
            //卡片列表配置
            table:{
                //卡片所有子表areacode 数组
                tableIds:['suplinkman','supcountrytaxes','supbankacc','finance','purchase'],
                suplinkman:{
                    tableName:this.Lang['10140SUG-000136'],/* 国际化处理： 联系人*/
                    tableId:'suplinkman',
                    relate:'agg',
                    property:{
                        modelSave: this.modelSave.bind(this,'suplinkman') || EMPTY_FUNC,
                        onBeforeEvent: this.onSupLinkmanTableBeforeEdit,
                        showIndex:true,
                        hideSwitch:()=>{return false}
                    },
                    btnApp:{
                        area: 'card_table',
                        buttonLimit: 3,
                        onButtonClick: onCardTableButtonClick.bind(this,'suplinkman'),
                        popContainer: document.querySelector('.card_table')
                    },
                    field:{
                        attrcode: 'opr',
                        label: this.Lang['10140SUG-000035'],/* 国际化处理： 操作*/
                        visible: true,
                        className:'table-opr',
                        width:200,
                        itemtype:'customer',
                        fixed:'right',
                        render: (text, record, index) => {
                            return (
                                <span fieldid="opr">
                                { (this.state.status =='edit' || this.state.status == 'add') && !this.state.disAssign &&
                                    <span
                                        className="row-edit-option"
                                        style={{'margin-right':'6px'}}
                                        onClick={()=>{this.onCardTableOperatEvent('suplinkman','assign',text,record,index)}}>
                                        {this.Lang['10140SUG-000242']/* 国际化处理： 分配组织*/}
                                        {/* <span className="split-line" style={{'margin-left':'6px'}}>|</span> */}
                                    </span>}
                                <span
                                    className="row-edit-option"
                                    style={{'margin-right':'6px'}}
                                    onClick={()=>{this.onCardTableOperatEvent('suplinkman',this.state.status ,text,record,index)}}>
                                    {this.Lang['10140SUG-000131']/* 国际化处理： 展开*/}
                                    {/* <span className="split-line" style={{'margin-left':'6px'}}>|</span> */}
                                </span>
                                { (this.state.status =='edit' || this.state.status == 'add') &&
                                    <span
                                        className="row-edit-option"
                                        onClick={()=>{this.onCardTableOperatEvent('suplinkman','delete',text,record,index)}}>
                                        {this.Lang['10140SUG-000209']/* 国际化处理： 删行*/}
                                    </span>

                                }
                                </span>
                            )
                        }
                    }
                },
                supcountrytaxes:{
                    tableName:this.Lang['10140SUG-000137'],/* 国际化处理： 国家税类*/
                    tableId:'supcountrytaxes',
                    relate:'agg',
                    property:{
                        modelSave: this.modelSave.bind(this,'supcountrytaxes') || EMPTY_FUNC,
                        showIndex:true,
                        hideSwitch:()=>{return false}
                    },
                    btnApp:{
                        area: 'card_table',
                        buttonLimit: 3,
                        onButtonClick: onCardTableButtonClick.bind(this,'supcountrytaxes'),
                        popContainer: document.querySelector('.card_table')
                    },
                    field:{
                        attrcode: 'opr',
                        label: this.Lang['10140SUG-000035'],/* 国际化处理： 操作*/
                        visible: true,
                        className:'table-opr',
                        width:200,
                        itemtype:'customer',
                        fixed:'right',
                        render: (text, record, index) => {
                            return (
                                <span  fieldid="opr">
                                 { (this.state.status =='edit' || this.state.status == 'add') &&
                                    <span
                                        className="row-edit-option"
                                        onClick={()=>{(this.state.status=='add' || this.state.status=='edit') && this.onCardTableOperatEvent('supcountrytaxes','delete',text,record,index)}}>
                                        {this.Lang['10140SUG-000209']/* 国际化处理： 删行*/}
                                    </span>
                                }
                                </span>

                            )
                        }
                    }
                },
                supbankacc:{
                    tableName:this.Lang['10140SUG-000138'],/* 国际化处理： 银行账户*/
                    tableId:'supbankacc',
                    relate:'inci',
                    property:{
                        modelSave: this.modelSave.bind(this,'supbankacc') || EMPTY_FUNC,
                        showIndex:true,
                        hideSwitch:()=>{return false},
                        //后增需求，双击银行账号弹出账号预览窗口，仅此表格有
                        onRowDoubleClick: this.supbankaccDoubleClick.bind(this,'supbankacc',statusProp.BROWSE),
                    },
                },
                finance:{
                    tableName:this.Lang['10140SUG-000112'],/* 国际化处理： 财务信息*/
                    tableId:'finance',
                    relate:'inci',
                    property:{
                        modelSave: this.modelSave.bind(this,'finance') || EMPTY_FUNC,
                        showIndex:true,
                        showCheck:true,
                        onSelected:this.onFinanceOrPurchaseTableSelected.bind(this,'finance'),
                        onSelectedAll:this.onFinanceOrPurchaseTableSelectedAll.bind(this,'finance'),
                        hideSwitch:()=>{return false},
                        onRowDoubleClick:this.onRowDoubleClick.bind(this,'finance',statusProp.BROWSE),
                    },
                    btnApp:{
                        area: 'supfinance_table',
                        buttonLimit: 3,
                        onButtonClick: onFinanceTableButtonClick.bind(this),
                        popContainer: document.querySelector('.supfinance_table')
                    },
                    field:{
                        attrcode: 'opr',
                        label: this.Lang['10140SUG-000035'],/* 国际化处理： 操作*/
                        visible: true,
                        className:'table-opr',
                        width:200,
                        itemtype:'customer',
                        fixed:'right',
                        // <span
                        //                 className="row-edit-option"
                        //                 onClick={()=>{(this.state.status!='add' && this.state.status!='edit') && this.onCardTableOperatEvent('finance','delete',text,record,index)}}>
                        //                 {this.Lang['10140SUG-000120']/* 国际化处理： 删行*/}
                        //             </span>
                        render: (text, record, index) => {
                            return (
                                <span  fieldid="opr">
                                {
                                    (this.state.status !='edit' && this.state.status != 'add') &&
                                    <span
                                        className="row-edit-option"
                                        onClick={()=>{(this.state.status!='add' && this.state.status !='edit') && this.onCardTableOperatEvent('finance','edit',text,record,index)}}>
                                        {this.Lang['10140SUG-000208']/* 国际化处理： 修改*/}
                                    </span>
                                }
                                {
                                    (this.state.status !='edit' && this.state.status != 'add') &&

                                    <NCPopconfirm
                                        trigger="click"
                                        placement="top"
                                        content={this.Lang['10140SUG-000072']}
                                        onClose = {
                                            ()=>{
                                                this.onCardTableOperatEvent('finance','delete',text,record,index)
                                            }
                                        }>
                                       <span className="row-edit-option">{this.Lang['10140SUG-000120']}</span>
                                    </NCPopconfirm>
                                }
                                </span>
                            )
                        }
                    },
                },
                purchase:{
                    tableName:this.Lang['10140SUG-000113'],/* 国际化处理： 采购信息*/
                    tableId:'purchase',
                    relate:'inci',
                    property:{
                        modelSave: this.modelSave.bind(this,'purchase') || EMPTY_FUNC,
                        showIndex:true,
                        showCheck:true,
                        onSelected:this.onFinanceOrPurchaseTableSelected.bind(this,'purchase'),
                        onSelectedAll:this.onFinanceOrPurchaseTableSelectedAll.bind(this,'purchase'),
                        hideSwitch:()=>{return false},
                        onRowDoubleClick:this.onRowDoubleClick.bind(this,'purchase',statusProp.BROWSE),
                    },
                    btnApp:{
                        area: 'supstock_table',
                        buttonLimit: 3,
                        onButtonClick: onStockTableButtonClick.bind(this),
                        popContainer: document.querySelector('.supstock_table')
                    },
                    field:{
                        attrcode: 'opr',
                        label: this.Lang['10140SUG-000035'],/* 国际化处理： 操作*/
                        visible: true,
                        className:'table-opr',
                        width:200,
                        itemtype:'customer',
                        fixed:'right',
                        //(this.state.status!='add' && this.state.status !='edit') && this.onCardTableOperatEvent('purchase','delete',text,record,index)
                        // <span
                        //                     className="row-edit-option"
                        //                     onClick={()=>{}}>
                        //                     {this.Lang['10140SUG-000120']/* 国际化处理： 删除*/}
                        //                 </span>
                        render: (text, record, index) => {
                            return (
                                <span  fieldid="opr">
                                {
                                    (this.state.status !='edit' && this.state.status != 'add') &&
                                    <span
                                        className="row-edit-option"
                                        onClick={()=>{(this.state.status!='add' && this.state.status !='edit') && this.onCardTableOperatEvent('purchase','edit',text,record,index)}}>
                                        {this.Lang['10140SUG-000208']/* 国际化处理： 修改*/}
                                    </span>
                                }
                                {
                                    (this.state.status !='edit' && this.state.status != 'add') &&
                                    <NCPopconfirm
                                        trigger="click"
                                        placement="top"
                                        content={this.Lang['10140SUG-000072']}
                                        onClose = {()=>{this.onCardTableOperatEvent('purchase','delete',text,record,index)}}>
                                       <span className="row-edit-option">{this.Lang['10140SUG-000120']}</span>
                                    </NCPopconfirm>

                                }
                                {
                                    (this.state.status !='edit' && this.state.status != 'add') &&
                                    <span
                                        //="DeleteLine"
                                        //fieldname={this.Lang['10140SUG-000207']/* 国际化处理： 地址簿*/}
                                        className="row-edit-option"
                                        onClick={()=>{(this.state.status!='add' && this.state.status !='edit') && this.onCardTableOperatEvent('purchase','address',text,record,index)}}>
                                        {this.Lang['10140SUG-000207']/* 国际化处理： 地址簿*/}
                                    </span>
                                }
                                </span>
                            )
                        }
                    }

                }
            }

        },
        //弹窗需要的配置
        dialog:{
            linkman:{
                formName:this.Lang['10140SUG-000136'],/* 国际化处理： 联系人*/
                formId:'linkman',
                targetId:'suplinkman',
                assignOrg:this.assignOrg.bind(this),
                refreshOrg:this.refreshOrg.bind(this)
            },
            supbankacc:{
                tableId:'custsupbankacc',
                tableName:this.Lang['10140SUG-000139'],/* 国际化处理： 供应商银行账户*/
                targetId:'supbankacc',
                pk_supplier:null,
            },
            supaddress:{
                tableId:'supaddress',
                tableName:this.Lang['10140SUG-000065'],/* 国际化处理： 供应商发货地址*/
                pk_supplier:null,
            },
            suprename:{
                tableId:'suprename',
                tableName:this.Lang['10140SUG-000234'],/* 国际化处理： 供应商更名记录*/
                pk_supplier:null,
            }
        },
        //打印配置
        printNodeKey:null,
        printUrl:null,
        printPks:null,
        tabList: initTabTitle.call(this, tempData.template),
        tabChildList: initChildTabTitle.call(this, tempData.template),
        rawTabList: deepClone(initTabTitle.call(this, tempData.template)),
        rawTabChildList: deepClone(initChildTabTitle.call(this, tempData.template))
    },{envParam:this.state.envParam,indivOrg:this.state.indivOrg,busiPortraitUrl:this.state.busiPortraitUrl});
    this.setState(this.state,() => {
        callback && callback.call(this);
    });
}

/*** 处理元数据项
* @param meta
 */
function dealMetaItems(meta){
    //联系人组织权限删除操作
    meta["SubjectOrg"] && meta["SubjectOrg"].items.push({
        attrcode: 'opr',
        label: this.Lang['dataTemplet-000002'],
        width: 200,
        fixed: 'right',
        className: 'table-opr',
        itemtype: 'customer',
        visible: true,
        render: (text, record, index) => {
            return <a fieldid="del-linkman" onClick={()=>this.deletePromptBox(record.pk_org.value)}>{this.Lang['10140SUG-000071']}</a>
        }
    })
    const addOperateField = (meta) =>{
        meta['finance'].items.push(this.state.card.table.finance.field);//财务信息列表操作列
        meta['purchase'].items.push(this.state.card.table.purchase.field);//采购信息列表操作列
    };
    dealRefTemplateItems.call(this,meta);//处理参照
    setCodeAndDeleteStatusFieldLink.call(this,meta);//设置编码和删除状态链接
    addOperateField(meta);//添加操作列
    //设置供应商银行账户 基本信息和网银信息的formrelation关系
    meta.formrelation = !meta.formrelation ? new Object() : meta.formrelation;
    meta.formrelation['accbasinfo'] = ['netbankinfo'];
    this.setOrgAssignToCache();
};
/*pmFWCFu5nhKkBzYmrkBakSAM+Inca+/2SazZgz119uT/d0gZJMONgfRaOvs2SpQg*/
